var $ = getApp(), methods = require("../methods.js");
Page(Object.assign({}, methods, {
	data: {
		productList: [],
		freightList: [],
		couponList: [],
		couponrid:0,
		coupontype:1,
		address: [],
		needaddress:1,
		linkman:'',
		tel:'',
		freightkey: 0,
		freightprice: 0,
		pstimetext:'',
		freight_time:'',
		usescore: 0,
		totalprice: '0.00',
		goodsprice: 0,
		disprice: 0,
		dkmoney:0,
		couponmoney:0,
		isload: 0,
		storedata:[],
		storeid:'',
		storename:'',
		latitude:'',
		longitude:'',
		leadermoney:0,
		couponvisible:false,
		pstimeDialogShow:false,
		pstimeIndex:-1,
	},
	_onLoad: function () {
		var that = this;
			//获取产品信息
			$.get('kanjia/buy', { joinid: that.options.joinid}, function (res) {
				if (res.status == 0) {
					$.alert(res.msg)
				}
				var product = res.product
				var freightList = res.freightList
				var userinfo = res.userinfo
				var couponList = res.couponList
				var joininfo = res.joininfo
				that.setData({
					product: product,
					freightList:freightList,
					userinfo:userinfo,
					couponList:couponList,
					joininfo:joininfo,
					goodsprice: joininfo['now_price'],
					weight: product.weight,
					goodsnum: 1,
					dkmoney:userinfo.dkmoney,
					address:res.address,
					scorebdkyf:res.scorebdkyf,
					isload: 1,
					havetongcheng:res.havetongcheng
				});
				that.calculatePrice();
				if(res.needLocation==1){
					wx.getLocation({
						type: 'gcj02',
						success:function(res){
							var latitude = res.latitude
							var longitude = res.longitude
							for(var j in freightList){
								if(freightList[j].pstype == 1){
									var storedata = freightList[j].storedata
									if(storedata){
										for(var x in storedata){
											if(latitude && longitude && storedata[x].latitude && storedata[x].longitude){
												var juli = that.getDistance(latitude,longitude,storedata[x].latitude,storedata[x].longitude);
												storedata[x].juli = juli;
											}
										}
										storedata.sort(function(a,b){
											return a["juli"]-b["juli"];
										});
										for(var x in storedata){
											if(storedata[x].juli){
												storedata[x].juli = storedata[x].juli + '千米';
											}
										}
										freightList[j].storedata = storedata;
									}
								}
							}
							that.setData({freightList:freightList})
						}
					});
				}
			});
	},
	//积分抵扣
	scoredk: function (e) {
		var usescore = e.detail.value[0];
		if (!usescore) usescore = 0
		this.setData({ usescore: usescore });
		this.calculatePrice();

	},
	inputLinkman:function(e){
		this.setData({ linkman: e.detail.value });
	},
	inputTel:function(e){
		this.setData({ tel: e.detail.value });
	},
	inputBeizhu: function (e) {
		this.setData({
			beizhu: e.detail.value
		})
	},
	inputfield1: function (e) {
		this.setData({ field1: e.detail.value });
	},
	inputfield2: function (e) {
		this.setData({ field2: e.detail.value });
	},
	inputfield3: function (e) {
		this.setData({ field3: e.detail.value });
	},
	inputfield4: function (e) {
		this.setData({ field4: e.detail.value });
	},
	inputfield5: function (e) {
		this.setData({ field5: e.detail.value });
	},
	//选择收货地址
	chooseAddress: function () {
		$.goto('/pages/address/address?fromPage=buy&type='+(this.data.havetongcheng==1?'1':'0'));
	},
	//计算价格
	calculatePrice: function () {
		var that = this;
		var goodsprice = parseFloat(that.data.goodsprice);	//+商品总价
		var disprice = parseFloat(that.data.disprice);			//-会员折扣
		if (that.data.usescore) {
			var dkmoney = parseFloat(that.data.dkmoney);			//-积分抵扣
		} else {
			var dkmoney = 0;
		}
		var couponmoney = parseFloat(that.data.couponmoney)	//-优惠券抵扣 
		var address = that.data.address
		//算运费
		var freightdata = that.data.freightList[that.data.freightkey];
		if(freightdata.pstype!=1){
			var needaddress = 1;
		}else{
			var needaddress = 0;
		}
		that.setData({needaddress:needaddress})
		var freightprice = 0;
		if(freightdata.pstype==0){
			var ftype = freightdata.type;
			var freeset = freightdata.freeset
			var free_price = parseFloat(freightdata.free_price);
			var pricedata = freightdata.pricedata;
			pricedata = JSON.parse(pricedata)
			for (var i = 0; i < pricedata.length; i++) {
				var thisdata = pricedata[i];
				var region = thisdata['region'];
				var regionlist = region.split('];');
				for (var j = 0; j < regionlist.length; j++) {
					var regiondata = regionlist[j].split('[');
					if (regiondata[0] == '全国(默认运费)' || (regiondata[0] == address['province'] && (regiondata[1] == '全部地区' || $.inArray(address['city'], regiondata[1].split(','))))) {
						if(freeset==1 && free_price <=goodsprice){
							freightprice = 0;
						}else{
							if(ftype==1){ //按重量
								freightprice = parseFloat(thisdata.fristprice);   //首重价格
								if (that.data.weight - parseFloat(thisdata.fristweight) > 0) {
									freightprice += Math.ceil((that.data.weight - parseFloat(thisdata.fristweight)) / parseFloat(thisdata.secondweight)) * parseFloat(thisdata.secondprice)  //+续重价格
								}
							}else{ //按件数
								freightprice = parseFloat(thisdata.fristprice);   //首件价格
								if (that.data.goodsnum - parseFloat(thisdata.fristweight) > 0) {
									freightprice += Math.ceil((that.data.goodsnum - parseFloat(thisdata.fristweight)) / parseFloat(thisdata.secondweight)) * parseFloat(thisdata.secondprice)  //+续件价格
								}
							}
						}
					}
				}
			}
		}else if(freightdata.pstype==1){//自提
			var storedata = freightdata.storedata;
			var storeid = storedata[0].id;
			var storename = storedata[0].name;
			var latitude = storedata[0].latitude
			var longitude = storedata[0].longitude
			that.setData({storedata:storedata,storeid:storeid,storename:storename,latitude:latitude,longitude:longitude})
		}else if(freightdata.pstype==2){ //同城配送
			var freeset = freightdata.freeset
			var free_price = parseFloat(freightdata.free_price);
			freightprice = freightdata.freightprice
			if(freeset==1 && free_price <= goodsprice){
				freightprice = 0;
			}
		}
		if(that.data.coupontype==4){
			freightprice = 0;
			couponmoney = 0;
		}
		var totalprice = goodsprice - disprice - couponmoney;
		if(totalprice < 0) totalprice = 0;  //优惠券不抵扣运费
		totalprice = totalprice	+ freightprice - dkmoney;
		if(that.data.scorebdkyf=='1' && dkmoney > 0 && totalprice < freightprice) totalprice = freightprice; //积分不抵扣运费
		if (totalprice < 0) totalprice = 0;
		freightprice = freightprice.toFixed(2)
		totalprice = totalprice.toFixed(2)
		that.setData({ totalprice: totalprice, freightprice: freightprice })
	},
	chooseFreight:function(e){
		var that = this;
		var itemlist = [];
		var freightList = this.data.freightList;
		for(var i=0;i<freightList.length;i++){
			itemlist.push(freightList[i].name);
		}
		wx.showActionSheet({
			itemList:itemlist,
			success:function (res) {
				that.setData({ freightkey: res.tapIndex });
				that.calculatePrice();
			}
		});
	},
	chooseCoupon:function(e){
		var couponrid = e.currentTarget.dataset.id;
		var couponkey = e.currentTarget.dataset.key;
		if(couponrid == this.data.couponrid){
			this.setData({ couponkey: 0,couponrid:0,coupontype:1, couponmoney: 0,couponvisible:false});
		}else{
			var couponList = this.data.couponList;
			var couponmoney = couponList[couponkey]['money']
			var coupontype = couponList[couponkey]['type']
			if(coupontype==4){
				couponmoney = this.data.freightprice
			}
			this.setData({ couponkey: couponkey,couponrid:couponrid,coupontype:coupontype, couponmoney: couponmoney,couponvisible:false});
		}
		this.calculatePrice();
	},
	choosePstime:function(){
		var that = this;
		var freightkey = this.data.freightkey;
		var freightList = this.data.freightList;
		var freight = freightList[freightkey]
		var pstimeArr = freightList[freightkey].pstimeArr
		var itemlist = [];
		for(var i=0;i<pstimeArr.length;i++){
			itemlist.push(pstimeArr[i].title);
		}
		if(itemlist.length == 0){
			$.alert('当前没有可选'+(freightList[freightkey].pstype==1?'取货':'配送')+'时间段');
			return;
		}
		if(itemlist.length > 6){
			that.setData({pstimeDialogShow:true,pstimeIndex:-1})
		}else{
			wx.showActionSheet({
				itemList:itemlist,
				success:function(res) {
					var choosepstime = pstimeArr[res.tapIndex]
					that.setData({ pstimetext: choosepstime.title,freight_time:choosepstime.value});
				}
			});
		}
	},
	pstimeRadioChange:function(e){
		this.setData({pstimeIndex:e.detail.value})
	},
	pstimeSelectConfirm:function(){
		var that = this;
		var pstimeIndex = that.data.pstimeIndex
		var freightkey = this.data.freightkey;
		var freightList = this.data.freightList;
		var freight = freightList[freightkey]
		var pstimeArr = freightList[freightkey].pstimeArr
		if(pstimeIndex == -1){
			$.error('请选择'+(freightList[freightkey].pstype==1?'取货':'配送')+'时间');return;
		}
		var choosepstime = pstimeArr[pstimeIndex]
		that.setData({ pstimetext: choosepstime.title,freight_time:choosepstime.value});
		that.setData({pstimeDialogShow:false})
	},
	hidePstimeDialog:function(){
		this.setData({pstimeDialogShow:false})
	},
	choosestore:function(e){
		var storeid = e.detail.value;
		var storedata = this.data.storedata
		var storename = '';
		var latitude = '';
		var longitude = '';
		for(var i in storedata){
			if(storedata[i].id == storeid){
				storename = storedata[i].name;
				latitude = storedata[i].latitude;
				longitude = storedata[i].longitude;
			}
		}
		this.setData({storeid:e.detail.value,storename:storename,latitude:latitude,longitude:longitude})
	},
	//提交并支付
	topay: function () {
		var that = this;
		var buytype = this.data.buytype;
		var freightkey = this.data.freightkey;
		var freightid = this.data.freightList[freightkey].id
		var joinid = this.options.joinid;
		var addressid = this.data.address.id
		var linkman = this.data.linkman;
		var tel = this.data.tel;
		var beizhu = this.data.beizhu
		var field1 = this.data.field1
		var field2 = this.data.field2
		var field3 = this.data.field3
		var field4 = this.data.field4
		var field5 = this.data.field5
		var usescore = this.data.usescore
		var couponkey = this.data.couponkey;
		var couponrid = this.data.couponrid
		var storeid = that.data.storeid;
		var freight_time = that.data.freight_time;
		//console.log(yhqrecoid); return;
		var needaddress = that.data.needaddress
		if(needaddress==0) addressid = 0;
		if (needaddress==1 && addressid == undefined) {
			$.error('请选择收货地址'); return;
		}
		if(this.data.freightList[freightkey].pstimeset==1 && freight_time==''){
			$.error('请选择'+(this.data.freightList[freightkey].pstype==0?'配送':'提货')+'时间'); return;
		}
		if(this.data.freightList[freightkey].pstype==1 && storeid==''){
			$.error('请选择自提地点'); return;
		}
		$.post('kanjia/createOrder', { joinid: joinid, couponrid: couponrid, freightid: freightid,freight_time:freight_time,storeid:storeid, addressid: addressid, message: beizhu, usescore: usescore,linkman:linkman,tel:tel,field1:field1,field2:field2,field3:field3,field4:field4,field5:field5}, function (data) {
			if (data.status == 0) {
				//that.showsuccess(res.data.msg);
				$.error(data.msg);
				return;
			}
			$.goto('/pages/wxpay/kanjiapay?id=' + data.orderid);
			/*
			if (data.status == 2) { //无需付款
					$.success(data.msg);
					setTimeout(function () {
							$.redirect('orderlist');
					}, 1000)
					return;
			}
			var opt = data.data;
			wx.requestPayment({
					'timeStamp': opt.timeStamp,
					'nonceStr': opt.nonceStr,
					'package': opt.package,
					'signType': 'MD5',
					'paySign': opt.paySign,
					'success': function (res) {
							$.success('付款完成');
							setTimeout(function () {
									$.redirect('orderlist');
							}, 1000)
					},
					'fail': function (res) {
					}
			})
			*/
		},'提交中')
	},
	showCouponList:function(){
		this.setData({couponvisible:true})
	},
	handleClickMask:function(){
		this.setData({couponvisible:false})
	},
}));